package com.atguigu.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * 日志过滤器 记录请求的历史 把日志打印到控制台上
 * <p>
 * 1 实现filter接口
 * 2 重写过滤方法、
 * 3 配置过滤器 (web.xml / 注解)
 */
public class LoggingFilter implements Filter {

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 过滤请求和响应的方法
        // 请求到达目标资源之前,先经过该方法
        //      可能的功能代码：判断是否登录、校验权限是否满足 ...
        System.out.println("LoggingFilter before filterChain.doFilter invoked");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        String dataTime = dateFormat.format(new Date());
        String beforeLogging = requestURI + "在" + dataTime + "被访问了";
        System.out.println(beforeLogging);

        LocalDateTime localDateTime1 = LocalDateTime.now();
        // 该方法有能力控制请求是否继续向后到达目标资源
        // 也可以在该方法内直接对客户端做响应处理
        //      放行代码,没有放行代码,请求到此为止
        filterChain.doFilter(servletRequest, servletResponse);
        // 请求到达目标资源后,响应之前,还会经过该方法
        //      响应之前,HttpServiceResponse转换为响应报文之前,的功能代码
        LocalDateTime localDateTime2 = LocalDateTime.now();
        Duration duration = Duration.between(localDateTime1, localDateTime2);
        String afterLogging = requestURI + "资源在" + dataTime + "的请求,耗时" + duration.toMillis() + "毫秒";
        System.out.println("LoggingFilter after filterChain.doFilter invoked");
        System.out.println(afterLogging);
    }
}
